import fs from 'fs'
import pool from '../database/index.js';
import { SplicingImagePaths } from '../utils/tools.js'

/**查询各种类文章数量 */
export const getNoteCount = async(req,res)=>{
    try{
      const [result,field] = await pool.execute(`SELECT channel AS name,COUNT(category) AS value from notelist 
      LEFT JOIN channel ON category=channel.id GROUP BY category `)
      res.send({ msg:'请求成功',code:200,data:{ message:'查询成功',list:result } })
    }catch(error){
      console.log(`接口${req.path}出现错误,错误为${error}`)
      res.status(500).send({ msg:'请求失败',code:500,data:{ message:'查询失败' } })
    }
}

/**
 * 获取频道列表
 */
export const getCategory = async(req,res)=>{
      try {
        const [result,fields] = await pool.query(`SELECT * FROM channel`)
        res.send({ msg:'请求成功',code:200,data:{ message:'查询成功',list:result } })
      } catch (error) {
        console.log(`接口${req.path}出现错误,错误为${error}`)
        res.status(500).send({ msg:'请求失败',code:500,data:{ message:'查询失败' } })
      }
}


/**获取文章列表 */
export const getNoteList = async(req,res)=>{
     const { sort,page,size } = req.query
     let type = sort ? sort : 3
     let currpage = page ? page : 1
     let pageSize = size ? size : 6
     try{
       const [result,field] = await pool.execute(`SELECT notelist.id,title,note,timestamp,nickname,avatar,cover
        FROM notelist LEFT JOIN user_info ON notelist.uid=user_info.userId   WHERE category=${type} ORDER BY id ASC
        LIMIT ${(currpage-1)*pageSize},${pageSize} `)
       const [cateResult,cateField] = await pool.execute(`SELECT COUNT(category) AS total FROM notelist  
        GROUP BY category HAVING category=${sort}`) 
        let total = cateResult.length ? cateResult[0].total :0
        const list = SplicingImagePaths(result,['avatar','cover'])
       res.send({ msg:'请求成功',code:200,data:{ message:'查询成功',list,total} })
     }catch(error){
       console.log(`接口${req.path}接口出现错误，错误为${error}`)
       res.status(400).send({ msg:'请求失败',code:400,data:{ message:'获取文章列表失败' } })
     }
}

/**获取文章详情 */
export const getNote = async(req,res)=>{
    const { id } = req.query
    try {
       const [result,field] = await pool.execute(`SELECT notelist.id,title,note,timestamp,nickname,avatar,userId AS author FROM notelist 
        LEFT JOIN user_info ON notelist.uid=user_info.userId WHERE notelist.id=${id}`)
        const list = SplicingImagePaths(result)
        if(!list.length) return res.status(500).send({ code:500,msg:'请求失败',data:{ message:'文章不存在，请检查参数' } })
        res.send({ msg:'请求成功',code:200,data:{ message:'请求成功',specs:list[0] } })
    } catch (error) {
        console.log(`接口${req.path}接口出现错误，错误为${error}`)
        res.status(400).send({ msg:'请求失败',code:400,data:{ message:'获取文章详情失败' } })
    }    
}

/**发布文章 */
export const publicNote = async(req,res)=>{
      const { userId } = req
      const { title,content,sort } = req.body
      const keys = Object.keys(req.body).map(item=>req.body[item])
      const params = keys.every(item=>item)
      if(!params) return res.status(500).send({ msg:'发布失败',code:500,data:{ message:'所需参数不全' } })
      try{
          await pool.execute(`INSERT INTO notelist (title,note,category,uid,timestamp) 
           VALUES (?,?,?,?,NOW())`,[title,content,sort,userId])
           res.send({ msg:'请求成功',code:200,data:{ message:'发布成功' } })
      }catch(error){
           console.log(`接口${req.path}出现错误，错误为${error}`)
           res.status(500).send({ msg:'发布失败',code:500,data:{ message:'发布文章失败' } })
      }
}

/**删除文章 */
export const deleteNote = async(req,res)=>{
    const { id } = req.body
    try{
      await pool.execute(`DELETE FROM notelist WHERE id=${id}`)
      res.send({ msg:'请求成功',code:200,data:{ message:'删除成功' } })
    }catch(error){
      console.log(`接口${req.path}出现错误,错误为${error}`)
      res.status(500).send({ msg:'删除失败',code:500,data:{ message:'删除文章失败' } })
    }
}

/**搜索文章 */
export const searchNote = async(req,res)=>{
      const { text } = req.query  
      const [result,fields] = await pool.execute(`SELECT id,title,note,timestamp,category FROM notelist 
         WHERE title LIKE '%${text}%' LIMIT 0,10`)
     res.send({ msg:'查询成功',code:200,data:{ message:'查询成功',list:result } })   
}